<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/7/16
 * Time: 10:14
 */
namespace app\index\controller;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use think\Controller;
use think\Request;

class Search extends Controller{

	public function test(){
		$client = ClientBuilder::create()->build();
		
//	$res = $this->index($client);
//$res = $this->get($client);
 $res = $this->search($client);
// $res = $this->deleteDoc($client);
// $res = $this->deleteIndex($client);
// $res = $this->createIndex($client);
		dump($res);
	}
	function index($client) {
		$params = array ();
		$params ['body'] = array (
			'testField' => 'abcsadfasdfsdafsadfsdaf'
		);
		$params ['index'] = 'my_index';
		$params ['type'] = 'my_type';
		$params ['id'] = time();
		try {
			$ret = $client->index($params);
			$this->println("create index success");
		} catch(Exception $e) {
			echo $e->getMessage();
		}
	}
	
	function get($client) {
		$getParams = array ();
		$getParams ['index'] = 'my_index';
		$getParams ['type'] = 'my_type';
		$getParams ['id'] = 'my_id';
		$retDoc = $client->get($getParams);
		$this->println($retDoc);
	}
	
	function search($client) {
		$searchParams ['index'] = 'my_index';
		$searchParams ['type'] = 'my_type';
		$searchParams ['body'] ['query'] ['match'] ['testField'] = 'abc';
		$retDoc = $client->search($searchParams);
		$this->println($retDoc);
	}
	
	function deleteDoc($client) {
		$deleteParams = array ();
		$deleteParams ['index'] = 'my_index';
		$deleteParams ['type'] = 'my_type';
		$deleteParams ['id'] = 'my_id';
		$retDelete = $client->delete($deleteParams);
		$this->println($retDelete);
	}
	
	function deleteIndex($client) {
		$deleteParams = array ();
		$deleteParams ['index'] = 'my_index';
		$retDelete = $client->indices()->delete($deleteParams);
		$this->println($retDelete);
	}
	
	function createIndex($client) {
		$indexParams ['index'] = 'my_index';
		$indexParams ['body'] ['settings'] ['number_of_shards'] = 2;
		$indexParams ['body'] ['settings'] ['number_of_replicas'] = 0;
		$retCreate = $client->indices()->create($indexParams);
		$this->println($retCreate);
	}
	
	function println($var) {
		echo "<br>";
		$type = gettype($var);
		if ($type == "array" || $type == "object") {
			echo json_encode($var);
		} else {
			echo $var;
		}
		echo "<br>";
	}
}